package com.gopay.cashier.web.controller;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gopay.cashier.service.BankPayCallBackService;
import com.gopay.cashier.web.command.BankPayCallbackCommand;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.GatewaySource;
import com.gopay.common.constants.trans.GatewayVersion;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.pg.PgGsrtOrderTransDtl;
import com.gopay.common.exception.GopayException;
import com.gopay.common.gateway.manager.PgGsrtOrderTransDtlQueryManager;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.RSAEncoderUtil;
import com.gopay.common.util.ResponseUtils;
import com.gopay.remote.cps.notify.order.MerNotifyOrderRemoteService;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 14-2-25.
 */
//@Controller
public class CashierBackNotifyController extends BaseController {
    // 2017-10-13起作废 生产优化10期 基于httpclient 调用方式 被替换为 hessian 方式 见 spring-config-remote.xml 中的 /bgNotify
    // 2017-10-13后使用 CashierBgNotifyRemoteService 接口调用 CashierBgNotifyRespMsg callBgNotify(Map<String,String> param);
    protected final static Log logger = LogFactory.getLog(CashierBackNotifyController.class);

    @Resource(name = "bankPayCallBackService")
    private BankPayCallBackService bankPayCallBackService;
    
    @Resource(name = "pgGsrtOrderTransDtlQueryManager")
	private PgGsrtOrderTransDtlQueryManager pgGsrtOrderTransDtlQueryManager;
    @Resource(name = "merOrderNotifyClient")
    private MerNotifyOrderRemoteService merOrderNotifyClient;


    @RequestMapping("/remoting/BankPayCallback.shtml")
    public void backProcess(BankPayCallbackCommand command,HttpServletResponse response){
        printRequest("CashierBackNotifyController-backProcess");
        
        String plain = sign(command);
        logger.error("sign verify plain : "+ plain);
        try {
			if(!RSAEncoderUtil.verify(plain, command.getSign())){
				logger.error("sign is not fit, which orderId is "+ command.getOrderId());
				return;
			}else{
				 logger.error("sign verify success, which orderId is "+ command.getOrderId());
			}
		} catch (Exception e1) {
			logger.error("verify sign error", e1);
			return;
		}
        
        String resCode = null;
        try{
            logger.info("cashier callback receive:" + command.getOrderId()+" at "+ DateUtils.getCurrDate());
            boolean res = bankPayCallBackService.callBackProcess(command);
            resCode = res==true?ProcCodeConstants.PROC_CODE_100S1000:ProcCodeConstants.PROC_CODE_200F1002;
        }catch (GopayException e){
            logger.error(e.getMessage());
            resCode = e.getErrCode();
        }
       /* CpsGenMainOrder mainOrder = cpsGeneralMainOrderQueryDAO.find(CpsGenMainOrder.class,command.getOrderId());
		if (TxnStaCode.TXN_STA_CD_20000.value == mainOrder.getTxnStaCd()) {
			logger.error("判断是否G商融通充值。。");
			PgGsrtOrderTransDtl pgTransDtl = pgGsrtOrderTransDtlQueryManager
					.get(Long.valueOf(mainOrder.getTransDtlSq()));
			if (pgTransDtl != null 
					&& (StringUtils.equals(GatewaySource.GATEWAY_SOURCE_09.value, mainOrder.getGatewaySource())
							|| StringUtils.equals(GatewaySource.GATEWAY_SOURCE_10.value, mainOrder.getGatewaySource()))) {
				logger.error("G商融通充值,流水记录：" + pgTransDtl);
				// 增加后台通知
				try {
					merOrderNotifyClient.addNotify(mainOrder.getGopayOrderId(), false, "109");
					logger.error("G商融通充值处理成功，异步通知商户。gopayOrderId[" + mainOrder.getGopayOrderId() + "]");
				} catch (Exception e) {
					logger.error("G商融通充值处理-异步通知商户失败", e);
				}
			}
		}*/
        
        response(resCode,command.getOrderId(),response);
    }

    private void response(String resCode,String orderId,HttpServletResponse response){
        JSONObject json =  new JSONObject();
        if(StringUtils.isBlank(resCode))
            resCode = ProcCodeConstants.PROC_CODE_200F1002;

        String resMsg = dicProcCodeService.getProcCodeInfo(resCode).getMessage();
        json.accumulate("orderId", orderId);
        json.accumulate("resCode", resCode);
        json.accumulate("resMsg", resMsg);
        logger.info("cashier callback result ->resCode:"+resCode+",resMsg:"+resMsg+" for orderId:"+orderId+" at "+ DateUtils.getCurrDate());
        ResponseUtils.renderText(response, json.toString());
    }
    public String sign(BankPayCallbackCommand orderInfo) {
        StringBuffer sign = new StringBuffer();
        String orderId = orderInfo.getOrderId();
        String amt = orderInfo.getAmt();
        String retCode = orderInfo.getRetCode();
        String retMsg = orderInfo.getRetMsg();
        String payStatus = orderInfo.getPayStatus();
        String notifyNum = orderInfo.getNotifyNum();
        String cardType = orderInfo.getCardType();
        sign.append(orderId).append("|");
        sign.append(amt).append("|");
        sign.append(retCode).append("|");
        sign.append(retMsg).append("|");
        sign.append(payStatus).append("|");
        sign.append(notifyNum).append("|");
        sign.append(cardType);
        return sign.toString();
    }
}
